const mongoose = require('mongoose');
const { User, Student, Class, Dormitory, Attendance, DisciplinaryRecord, AuditLog, Department } = require('./models/db');
const bcryptjs = require('bcryptjs');

// 生成随机日期
function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

// 生成随机电话号码
function randomPhone() {
  return '1' + Math.floor(Math.random() * 9000000000 + 1000000000);
}

// 生成随机邮箱
function randomEmail(name) {
  const domains = ['gmail.com', 'qq.com', '163.com', '126.com', 'sina.com', 'outlook.com'];
  return name.toLowerCase().replace(/\s+/g, '') + Math.floor(Math.random() * 1000) + '@' + domains[Math.floor(Math.random() * domains.length)];
}

// 生成随机学生ID
function randomStudentId() {
  return '20' + Math.floor(Math.random() * 24 + 20) + Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
}

// 初始化数据
async function seedDatabase() {
  try {
    // 连接数据库
    await mongoose.connect('mongodb://localhost:27017/sms');
    console.log('数据库连接成功');

    // 清空现有数据
    await User.deleteMany({});
    await Student.deleteMany({});
    await Class.deleteMany({});
    await Dormitory.deleteMany({});
    await Attendance.deleteMany({});
    await DisciplinaryRecord.deleteMany({});
    await AuditLog.deleteMany({});
    await Department.deleteMany({});
    console.log('清空现有数据');

    // 1. 创建院系数据
    const departments = [
      { name: '计算机科学与技术学院', description: '培养计算机领域高级人才' },
      { name: '电子工程学院', description: '电子信息与电气工程领域教育' },
      { name: '经济管理学院', description: '经济与管理学科教育' },
      { name: '文学院', description: '人文社科类学科教育' },
      { name: '外国语学院', description: '外语语言与文化教育' }
    ];
    
    const departmentDocs = await Department.insertMany(departments);
    console.log('创建院系数据完成');

    // 2. 创建用户数据
    const users = [];
    // 测试阶段使用明文密码，暂不加密
    // const adminPassword = await bcryptjs.hash('admin123', 10);
    // const sysadminPassword = await bcryptjs.hash('sysadmin123', 10);
    // const deptheadPassword = await bcryptjs.hash('depthead123', 10);
    // const teacherPassword = await bcryptjs.hash('teacher123', 10);
    const adminPassword = 'admin123';
    const sysadminPassword = 'sysadmin123';
    const deptheadPassword = 'depthead123';
    const teacherPassword = 'teacher123';
    
    // 超级管理员
    users.push({
      username: 'admin',
      password: adminPassword,
      role: 'admin',
      email: 'admin@example.com',
      phone: '13800138000',
      lastLogin: randomDate(new Date(2024, 0, 1), new Date())
    });
    
    // 系统管理员
    users.push({
      username: 'sysadmin',
      password: sysadminPassword,
      role: 'admin',
      email: 'sysadmin@example.com',
      phone: '13800138001',
      lastLogin: randomDate(new Date(2024, 0, 1), new Date())
    });
    
    // 扩展院系数据（增加到10个院系以支持15个院长）
    const additionalDepartments = [
      { name: '机械工程学院', description: '机械制造与自动化领域教育' },
      { name: '材料科学与工程学院', description: '材料科学与工程教育' },
      { name: '化学工程学院', description: '化学工程与技术教育' },
      { name: '建筑学院', description: '建筑设计与规划教育' },
      { name: '艺术学院', description: '艺术与设计教育' }
    ];
    const allDepartmentDocs = [...departmentDocs, ...(await Department.insertMany(additionalDepartments))];
    console.log('创建扩展院系数据完成');

    // 各学院院长和主任（共15个）
    for (let i = 0; i < 15; i++) {
      const deptIndex = i < allDepartmentDocs.length ? i : Math.floor(Math.random() * allDepartmentDocs.length);
      users.push({
        username: `depthead${i + 1}`,
        password: deptheadPassword,
        role: i < 5 ? 'teacher' : 'admin', // 前5个是院长，后面是主任
        email: `depthead${i + 1}@example.com`,
        phone: randomPhone(),
        lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
        name: `院长${i + 1}`,
        position: i < 5 ? '院长' : '主任'
      });
    }
    
    // 教师和导员（共50个）
    const teacherRoles = ['teacher', 'teacher', 'teacher', 'muster']; // muster是导员
    const teacherPositions = ['讲师', '副教授', '教授', '导员', '班主任'];
    for (let i = 0; i < 50; i++) {
      const role = teacherRoles[Math.floor(Math.random() * teacherRoles.length)];
      users.push({
        username: `teacher${i + 1}`,
        password: teacherPassword,
        role: role,
        email: randomEmail(`Teacher${i + 1}`),
        phone: randomPhone(),
        lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
        name: `教师${i + 1}`,
        position: teacherPositions[Math.floor(Math.random() * teacherPositions.length)]
      });
    }
    
    const userDocs = await User.insertMany(users);
    console.log('创建用户数据完成');
    
    // 更新所有院系的负责人和教职工
    const deptHeadUsers = userDocs.slice(2, 17); // 15个院长和主任
    const teacherUsers = userDocs.slice(17); // 50个教师和导员
    
    for (let i = 0; i < allDepartmentDocs.length; i++) {
      if (i < deptHeadUsers.length) {
        allDepartmentDocs[i].head = deptHeadUsers[i]._id;
      }
      // 为每个院系分配5-10个教师
      const facultyCount = Math.floor(Math.random() * 6) + 5;
      const startIndex = i * 5;
      allDepartmentDocs[i].faculty = teacherUsers.slice(startIndex, startIndex + facultyCount).map(u => u._id);
      await allDepartmentDocs[i].save();
    }
    console.log('更新院系负责人和教职工完成');

    // 3. 创建宿舍数据
    const dormitories = [
      { dormitoryName: '学1舍' },
      { dormitoryName: '学2舍' },
      { dormitoryName: '学3舍' },
      { dormitoryName: '学4舍' },
      { dormitoryName: '学5舍' }
    ];
    const dormitoryDocs = await Dormitory.insertMany(dormitories);
    console.log('创建宿舍数据完成');

    // 4. 创建班级数据（需要等到userDocs创建后）
    const classNames = ['2409A', '2409B', '2410A', '2410B', '2411A', '2411B', '2412A', '2412B', '2501A', '2501B'];
    
    // 使用之前已定义的 teacherUsers
    const classes = [];
    
    for (let i = 0; i < classNames.length; i++) {
      classes.push({
        className: classNames[i],
        department: allDepartmentDocs[Math.floor(Math.random() * allDepartmentDocs.length)]._id,
        teacher: teacherUsers[Math.floor(Math.random() * teacherUsers.length)]._id,
        lecturerId: teacherUsers[Math.floor(Math.random() * teacherUsers.length)]._id,
        lecturerName: `讲师${Math.floor(Math.random() * 50) + 1}`,
        advisorId: teacherUsers.filter(u => u.role === 'muster')[Math.floor(Math.random() * teacherUsers.filter(u => u.role === 'muster').length)]?._id,
        advisorName: `导员${Math.floor(Math.random() * 50) + 1}`
      });
    }
    
    const classDocs = await Class.insertMany(classes);
    console.log('创建班级数据完成（10个班级）');

    // 5. 创建学生数据（100个）
    const students = [];
    const firstNames = ['张', '李', '王', '刘', '陈', '杨', '赵', '黄', '周', '吴', '徐', '孙', '马', '朱', '胡', '郭', '何', '高', '林', '罗'];
    const lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '军', '洋', '勇', '艳', '杰', '娟', '涛', '明', '超', '秀兰', '霞', '平'];
    const academies = ['人工智能', '数智传媒', '鸿蒙生态开发', '云计算', '元宇宙', '市场部'];
    const stages = ['freshman', 'sophomore', 'junior'];
    const statuses = ['active', 'suspended', 'graduated', 'transferred'];
    
    for (let i = 0; i < 100; i++) {
      const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
      const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
      const name = firstName + lastName + (i > 0 ? i : '');
      
      students.push({
        studentId: randomStudentId(),
        name: name,
        gender: Math.random() > 0.5 ? '男' : '女',
        dob: randomDate(new Date(2000, 0, 1), new Date(2005, 11, 31)),
        email: randomEmail(name),
        phone: randomPhone(),
        class: classDocs[Math.floor(Math.random() * classDocs.length)]._id,
        dormitory: dormitoryDocs[Math.floor(Math.random() * dormitoryDocs.length)]._id,
        major: allDepartmentDocs[Math.floor(Math.random() * allDepartmentDocs.length)].name + '专业',
        academy: academies[Math.floor(Math.random() * academies.length)],
        stage: stages[Math.floor(Math.random() * stages.length)],
        status: statuses[Math.floor(Math.random() * statuses.length)],
        admissionDate: randomDate(new Date(2020, 0, 1), new Date(2024, 0, 1)),
        address: `北京市朝阳区${Math.floor(Math.random() * 100)}号`
      });
    }
    
    const studentDocs = await Student.insertMany(students);
    console.log('创建学生数据完成（100个）');
    
    // 更新班级和宿舍的学生列表
    for (let i = 0; i < classDocs.length; i++) {
      classDocs[i].students = studentDocs.filter(s => s.class.toString() === classDocs[i]._id.toString()).map(s => s._id);
      await classDocs[i].save();
    }
    
    for (let i = 0; i < dormitoryDocs.length; i++) {
      dormitoryDocs[i].students = studentDocs.filter(s => s.dormitory.toString() === dormitoryDocs[i]._id.toString()).map(s => s._id);
      await dormitoryDocs[i].save();
    }
    console.log('更新班级和宿舍的学生列表完成');

    // 6. 创建考勤记录（增加数量以支持100个学生）
    const attendances = [];
    const attendanceStatuses = ['正常', '迟到', '早退', '缺席'];
    
    for (let i = 0; i < 500; i++) {
      const student = studentDocs[Math.floor(Math.random() * studentDocs.length)];
      attendances.push({
        student: student._id,
        date: randomDate(new Date(2024, 0, 1), new Date()),
        status: attendanceStatuses[Math.floor(Math.random() * attendanceStatuses.length)],
        class: student.class
      });
    }
    
    const attendanceDocs = await Attendance.insertMany(attendances);
    console.log('创建考勤记录完成');
    
    // 更新学生的考勤记录
    for (let i = 0; i < studentDocs.length; i++) {
      studentDocs[i].attendance = attendanceDocs.filter(a => a.student.toString() === studentDocs[i]._id.toString()).map(a => a._id);
      await studentDocs[i].save();
    }
    console.log('更新学生的考勤记录完成');

    // 7. 创建违纪记录（增加数量）
    const disciplinaryRecords = [];
    const descriptions = [
      '未按时参加早自习',
      '上课迟到',
      '宿舍卫生不合格',
      '未请假缺勤',
      '违反课堂纪律'
    ];
    const penalties = ['警告', '严重警告', '通报批评', '记过', '留校察看'];
    
    for (let i = 0; i < 50; i++) {
      const record = {
        student: studentDocs[Math.floor(Math.random() * studentDocs.length)]._id,
        date: randomDate(new Date(2024, 0, 1), new Date()),
        description: descriptions[Math.floor(Math.random() * descriptions.length)],
        penalty: penalties[Math.floor(Math.random() * penalties.length)]
      };
      disciplinaryRecords.push(record);
    }
    
    const disciplinaryDocs = await DisciplinaryRecord.insertMany(disciplinaryRecords);
    console.log('创建违纪记录完成');
    
    // 更新学生的违纪记录
    for (let i = 0; i < studentDocs.length; i++) {
      studentDocs[i].disciplinaryRecords = disciplinaryDocs.filter(d => d.student.toString() === studentDocs[i]._id.toString()).map(d => d._id);
      await studentDocs[i].save();
    }
    console.log('更新学生的违纪记录完成');

    // 8. 创建审计日志（增加数量）
    const auditLogs = [];
    const actions = ['登录', '修改数据', '查询数据', '添加数据', '删除数据'];
    const targets = ['学生信息', '班级信息', '考勤记录', '违纪记录', '用户权限'];
    
    for (let i = 0; i < 200; i++) {
      auditLogs.push({
        user: userDocs[Math.floor(Math.random() * userDocs.length)]._id,
        action: actions[Math.floor(Math.random() * actions.length)],
        target: targets[Math.floor(Math.random() * targets.length)],
        timestamp: randomDate(new Date(2024, 0, 1), new Date()),
        ip: `192.168.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`
      });
    }
    
    await AuditLog.insertMany(auditLogs);
    console.log('创建审计日志完成');

    console.log('数据库初始化完成！');
    mongoose.connection.close();
  } catch (error) {
    console.error('数据库初始化失败:', error);
    mongoose.connection.close();
  }
}

// 运行数据初始化
seedDatabase();